package com.soFun.config;

import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.embedding.EmbeddingModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.time.Duration;

/**
 * LangChain4j框架配置类
 */
@Configuration
@Slf4j
public class LangChain4jConfig {

    @Value("${langchain4j.openai.api-key}")
    private String openaiApiKey;

    /**
     * 配置OpenAI聊天模型
     * @return ChatLanguageModel实例
     */
    @Bean
    public ChatLanguageModel chatLanguageModel() {
        log.info("初始化OpenAI聊天模型...");
        try {
            // 尝试不同的可能的包路径
            Class<?> openAiModelClass;
            try {
                // 尝试dev.langchain4j.model.open.ai
                openAiModelClass = Class.forName("dev.langchain4j.model.open.ai.OpenAiChatModel");
                log.info("找到open.ai包中的OpenAiChatModel");
            } catch (ClassNotFoundException e1) {
                try {
                    // 尝试dev.langchain4j.model.openai
                    openAiModelClass = Class.forName("dev.langchain4j.model.openai.OpenAiChatModel");
                    log.info("找到openai包中的OpenAiChatModel");
                } catch (ClassNotFoundException e2) {
                    try {
                        // 也许是这个路径？
                        openAiModelClass = Class.forName("dev.langchain4j.openai.OpenAiChatModel");
                        log.info("找到openai根包中的OpenAiChatModel");
                    } catch (ClassNotFoundException e3) {
                        try {
                            // 或者这个？
                            openAiModelClass = Class.forName("dev.langchain4j.open.ai.OpenAiChatModel");
                            log.info("找到open.ai根包中的OpenAiChatModel");
                        } catch (ClassNotFoundException e4) {
                            log.error("无法找到OpenAiChatModel类，请检查依赖版本");
                            throw new RuntimeException("无法找到OpenAiChatModel类，请检查依赖版本", e4);
                        }
                    }
                }
            }
            
            // 获取builder方法
            Method builderMethod = openAiModelClass.getMethod("builder");
            Object builder = builderMethod.invoke(null);
            
            // 设置属性
            Class<?> builderClass = builder.getClass();
            
            Method apiKeyMethod = builderClass.getMethod("apiKey", String.class);
            builder = apiKeyMethod.invoke(builder, openaiApiKey);
            
            Method modelNameMethod = builderClass.getMethod("modelName", String.class);
            builder = modelNameMethod.invoke(builder, "gpt-3.5-turbo");
            
            Method temperatureMethod = builderClass.getMethod("temperature", double.class);
            builder = temperatureMethod.invoke(builder, 0.7);
            
            try {
                // 尝试设置logRequests
                Method logRequestsMethod = builderClass.getMethod("logRequests", boolean.class);
                builder = logRequestsMethod.invoke(builder, true);
                
                // 尝试设置logResponses
                Method logResponsesMethod = builderClass.getMethod("logResponses", boolean.class);
                builder = logResponsesMethod.invoke(builder, true);
                
                // 尝试设置timeout
                Method timeoutMethod = builderClass.getMethod("timeout", Duration.class);
                builder = timeoutMethod.invoke(builder, Duration.ofSeconds(60));
            } catch (NoSuchMethodException ex) {
                // 忽略可选方法不存在的情况
                log.warn("某些可选方法不存在: {}", ex.getMessage());
            }
            
            // 构建模型
            Method buildMethod = builderClass.getMethod("build");
            ChatLanguageModel model = (ChatLanguageModel) buildMethod.invoke(builder);
            
            log.info("OpenAI聊天模型初始化成功");
            return model;
        } catch (Exception e) {
            log.error("OpenAI聊天模型初始化失败: {}", e.getMessage(), e);
            throw new RuntimeException("OpenAI聊天模型初始化失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 配置嵌入模型
     * @return EmbeddingModel实例
     */
    @Bean
    public EmbeddingModel embeddingModel() {
        log.info("初始化嵌入模型...");
        try {
            Class<?> embeddingModelClass = Class.forName("dev.langchain4j.model.embedding.AllMiniLmL6V2EmbeddingModel");
            Constructor<?> constructor = embeddingModelClass.getConstructor();
            return (EmbeddingModel) constructor.newInstance();
        } catch (Exception e) {
            log.error("嵌入模型初始化失败: {}", e.getMessage(), e);
            throw new RuntimeException("嵌入模型初始化失败: " + e.getMessage(), e);
        }
    }
} 